package com.zss.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zss.admin.service.AccountantService;
import com.zss.poi.AccountantPOIUtils;
import com.zss.pojo.*;
import com.zss.staff.service.AreaService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Controller
@RequestMapping("admin/accountant")
public class AccountantController {

    @Resource
    AccountantService accountantService;

    @Resource
    AreaService areaService;
    /**
     * 进入列表页面
     * @return
     */
    @RequestMapping("list")
    public String list(){
        return "admin/accountant/list";
    }

    /**
     * 获取列表数据
     * @return
     */
    @RequestMapping("getList")
    @ResponseBody
    public List<Accountant> getList(@RequestBody Accountant accountant){

        LambdaQueryWrapper<Accountant> queryWapper = new LambdaQueryWrapper<Accountant>();
        if(StringUtils.isNotBlank(accountant.getAname())){
            queryWapper.eq(Accountant::getAname,accountant.getAname());
        }

        if(accountant.getCreateTime()!=null){
            int year = accountant.getCreateTime().getYear()+1900;
            int month = accountant.getCreateTime().getMonth()+1;
            LocalDate today = LocalDate.of(year,month,accountant.getCreateTime().getDate());// 获取当前日期
            LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月最后一天
            // ge是大于等于5月1日的数据，le是小于等于本月最后一天的数据
            System.out.println(today);
            System.out.println("today=====");
            queryWapper.ge(Accountant::getCreateTime,today).le(Accountant::getCreateTime,lastDayOfMonth);
        }
        return accountantService.list(queryWapper);
    }



    /**
     * 添加或修改
     * @param
     */
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public boolean add(@RequestBody Accountant accountant){
        LambdaQueryWrapper<Accountant> queryWapper = new LambdaQueryWrapper<Accountant>();
        if(StringUtils.isNotBlank(accountant.getAname())){
            queryWapper.eq(Accountant::getAname,accountant.getAname());
        }

        if(accountant.getCreateTime()!=null){
            int year = accountant.getCreateTime().getYear()+1900;
            int month = accountant.getCreateTime().getMonth()+1;
            LocalDate today = LocalDate.of(year,month,accountant.getCreateTime().getDate());// 获取当前日期
            LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月最后一天
            // ge是大于等于5月1日的数据，le是小于等于本月最后一天的数据
            queryWapper.ge(Accountant::getCreateTime,today).le(Accountant::getCreateTime,lastDayOfMonth);
        }
        List<Accountant> list = accountantService.list(queryWapper);
        if(accountant.getId()==null){ // 走的添加
            if(list.size()>0){
                return false;
            }
        }else{ // 走的修改
            if(list.size()>0 && list.get(0).getId()!=accountant.getId() && list.get(0).getAname().equals(accountant.getAname())){
                return false;
            }
        }

        accountantService.saveOrUpdate(accountant);
        return true;
    }

    /**
     * 区域回显
     * @param id
     * @return
     */
    @RequestMapping("findById/{id}")
    @ResponseBody
    public Accountant findById(@PathVariable Long id){
        return accountantService.getById(id);
    }

    @RequestMapping("downloadTemplate")
    @ResponseBody
    public void downloadTemplate( HttpServletResponse response){
        AccountantPOIUtils.downloadTemplate(response);
    }


    @RequestMapping("export")
    @ResponseBody
    public void export( HttpServletResponse response,
                        @RequestParam("aname")String aname,
                        @RequestParam("createTime")@DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime
                        ){

        LambdaQueryWrapper<Accountant> queryWapper = new LambdaQueryWrapper<Accountant>();
        if(StringUtils.isNotBlank(aname)){
            queryWapper.eq(Accountant::getAname,aname);
        }

        if(createTime!=null){
            int year = createTime.getYear()+1900;
            int month = createTime.getMonth()+1;
            LocalDate today = LocalDate.of(year,month,createTime.getDate());// 获取当前日期
            LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月最后一天
            // ge是大于等于5月1日的数据，le是小于等于本月最后一天的数据
            queryWapper.ge(Accountant::getCreateTime,today).le(Accountant::getCreateTime,lastDayOfMonth);
        }
        List<Accountant> list = accountantService.list(queryWapper);
        AccountantPOIUtils.export(response,list);
    }


    @RequestMapping("importAccountant")
    @ResponseBody
    public Map<String,Object> importAccountant(HttpServletRequest request,
                                                HttpServletResponse response,
                                                @RequestBody MultipartFile importAccountantFile){

        List<Accountant> list = new ArrayList<Accountant>();

        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Workbook wb = new XSSFWorkbook(importAccountantFile.getInputStream());
            // 读取第一个Sheet
            Sheet sheetAt = wb.getSheetAt(0);
            // 总共的行数
            int rowLens = sheetAt.getLastRowNum();
            /**
             * 检查数据格式是否有问题
             */
            List<String> importMsgList = new ArrayList<String>();
            for (int rowCount = 4; rowCount <= rowLens; rowCount++) {  // 校验数据格式是否有问题
                Row row = sheetAt.getRow(rowCount);
                if (row != null) {
                    checkValue(row,rowCount,importMsgList);
                }
            }
            if(importMsgList.size()>0){ // 导入错误只展示15条错误记录
                if(importMsgList.size()>14){
                    map.put("list",importMsgList.subList(0,15));
                }else{
                    map.put("list",importMsgList);
                }
                return map;
            }
            /**
             * 得到数据，处理数据
             */
            for (int rowCount = 4; rowCount <= rowLens; rowCount++) {
                Row row = sheetAt.getRow(rowCount);
                if (row != null) {
                    Accountant accountant = getCellValue(row, rowCount);
                    if(accountant!=null){
                        list.add(accountant);
                    }
                }
            }
            // 导入的数据批量添加数据库中
            accountantService.saveBatch(list);

            importMsgList.add("导入成功");
            map.put("list",importMsgList);
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void checkValue(Row row, int rowCount, List<String> importMsgList) {
        Accountant accountant = new Accountant();



        try {
            Cell cellTime = row.getCell((short) 0);
            Date dateCellValue = cellTime.getDateCellValue();
            if(dateCellValue==null){ // 这行干什么用的，检查空数据用的
                return;
            }
            accountant.setCreateTime(dateCellValue);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第A列日期数据格式有问题");
        }

        try {
            Cell cellArea = row.getCell((short) 1);
            String areCellValue = cellArea.getStringCellValue();
            accountant.setAname(areCellValue);

            LambdaQueryWrapper<TbArea> queryWrapper = new LambdaQueryWrapper<TbArea>();
            queryWrapper.eq(TbArea::getName,areCellValue.trim());
            List<TbArea> list = areaService.list(queryWrapper);
            if(list==null || list.size()==0){
                importMsgList.add("第"+rowCount+"行,第B列地区数据不存在");
            }
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第B列地区数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 2);
            double commission = cellPrice.getNumericCellValue();
            accountant.setCommission((int)commission);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第C列提成数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 3);
            double insurance = cellPrice.getNumericCellValue();
            accountant.setInsurance((int)insurance);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第D列保险费数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 4);
            double operate = cellPrice.getNumericCellValue();
            accountant.setOperate((int)operate);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第E列经营费用数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 5);
            double vehicle = cellPrice.getNumericCellValue();
            accountant.setVehicle((int)vehicle);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第F列大车费用数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 6);
            double loadings = cellPrice.getNumericCellValue();
            accountant.setLoadings((int)loadings);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第G列装卸组数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 7);
            double returnIncome = cellPrice.getNumericCellValue();
            accountant.setReturnIncome((int)returnIncome);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第H列返程收入数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 8);
            double totalFreight = cellPrice.getNumericCellValue();
            accountant.setTotalFreight((int)totalFreight);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第I列总运费数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 9);
            double companyClaims = cellPrice.getNumericCellValue();
            accountant.setCompanyClaims((int)companyClaims);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第J列公司理赔数据格式有问题");
        }

        try {
            Cell cellPrice = row.getCell((short) 10);
            double branchClaims = cellPrice.getNumericCellValue();
            accountant.setBranchClaims((int)branchClaims);
        }catch (Exception e){
            importMsgList.add("第"+rowCount+"行,第K列分公司理赔数据格式有问题");
        }

        LambdaQueryWrapper<Accountant> queryWapper = new LambdaQueryWrapper<Accountant>();
        queryWapper.eq(Accountant::getAname,accountant.getAname());

        int year = accountant.getCreateTime().getYear()+1900;
        int month = accountant.getCreateTime().getMonth()+1;
        LocalDate today = LocalDate.of(year,month,1);
        LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月最后一天
        // ge是大于等于5月1日的数据，le是小于等于本月最后一天的数据
        queryWapper.ge(Accountant::getCreateTime,today).le(Accountant::getCreateTime,lastDayOfMonth);
        List<Accountant> accountantList = accountantService.list(queryWapper);
        if(accountantList.size()>0){
            importMsgList.add("第"+rowCount+"行,日期或地址数据已存在，请修改后导入");
            return;
        }

    }

    public Accountant getCellValue(Row row,int rowCount) {
        Accountant accountant = new Accountant();
        Cell cellTime = row.getCell((short) 0);
        Date dateCellValue = cellTime.getDateCellValue();
        accountant.setCreateTime(dateCellValue);
        if(dateCellValue==null){ // 校验格式那里返回了，如果这里不做处理，就会导入很多空数据
            return null;
        }

        Cell cellArea = row.getCell((short) 1);
        String areCellValue = cellArea.getStringCellValue();
        accountant.setAname(areCellValue);

        LambdaQueryWrapper<TbArea> queryWrapper = new LambdaQueryWrapper<TbArea>();
        queryWrapper.eq(TbArea::getName,areCellValue.trim());
        List<TbArea> list = areaService.list(queryWrapper);
        accountant.setAid(list.get(0).getId());

        Cell cellcommission = row.getCell((short) 2);
        double commission = cellcommission.getNumericCellValue();
        accountant.setCommission((int)commission);


        Cell cellInsurance = row.getCell((short) 3);
        double insurance = cellInsurance.getNumericCellValue();
        accountant.setInsurance((int)insurance);

        Cell cellOperate = row.getCell((short) 4);
        double operate = cellOperate.getNumericCellValue();
        accountant.setOperate((int)operate);

        Cell cellVehicle = row.getCell((short) 5);
        double vehicle = cellVehicle.getNumericCellValue();
        accountant.setVehicle((int)vehicle);

        Cell cellLoadings = row.getCell((short) 6);
        double loadings = cellLoadings.getNumericCellValue();
        accountant.setLoadings((int)loadings);

        Cell cellReturnIncome = row.getCell((short) 7);
        double returnIncome = cellReturnIncome.getNumericCellValue();
        accountant.setReturnIncome((int)returnIncome);

        Cell cellTotalFreight = row.getCell((short) 8);
        double totalFreight = cellTotalFreight.getNumericCellValue();
        accountant.setTotalFreight((int)totalFreight);

        Cell cellCompanyClaimse = row.getCell((short) 9);
        double companyClaims = cellCompanyClaimse.getNumericCellValue();
        accountant.setCompanyClaims((int)companyClaims);

        Cell cellBranchClaims = row.getCell((short) 10);
        double branchClaims = cellBranchClaims.getNumericCellValue();
        accountant.setBranchClaims((int)branchClaims);
        return accountant;
    }



    /**
     * 更新状态
     * @param id
     */
//    @RequestMapping("updateStatus/{id}/{status}")
//    @ResponseBody
//    public void updateStatus(@PathVariable int id,@PathVariable String status){
//        LambdaQueryWrapper<Accountant> queryWarpper = new LambdaQueryWrapper<Accountant>();
//        queryWarpper.eq(Accountant::getId,id);
//        Accountant accountant = new Accountant();
//        accountant.setStatus(status);
//        accountantService.update(accountant,queryWarpper);
//    }

}
